<template>
  <div class="register"  @click="bodyClose($event)">
    <div class="register-content">
      <ztitleBorder title="患者信息">
        <div class="search-head">
          <div class="search" ref="searchArea" >
            <el-input placeholder="搜索患者"  v-model="info" @input="querySearch">
              <template #prepend >
                <el-icon><search /></el-icon>
              </template>
            </el-input>
            <div class="info-plan" v-if="isShowPlan" ref="infoPlan">
              <el-empty v-if="!personList.length" description="暂无数据" style="width:100%; height: 180px"></el-empty>
              <div v-else class="plan" v-for="item in personList" :key="item">
                <searchItem @searchItem="handleItem" :showRegister="false" :searchData="item"></searchItem>
              </div>
            </div>
          </div>
          <div class="btns" @click="handlebtn">
            <span><el-icon><plus /></el-icon></span>
          </div>
        </div>
        <div class="search-ctx">
          <div class="callapse">
            <div class="show-head" @click="handleShow">
              <span class="head-ctx">
                  <!-- <component :is="showWidget(item.type)"  v-for="item in firstThreeData" :key="item.name" :struc="item"  /> -->
                  <span class="name">{{info}}</span>
                  <span class="sex">
                    <el-icon v-if="sex === '男'" class="male-color"><male /></el-icon>
                    <el-icon v-if="sex === '女'" class=" female-color"><female /></el-icon>
                  </span>
              </span>
              <span class="icon-btn">
                <el-icon v-if="isShow"><arrow-right /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
              </span>
              
            </div>
            <div class="show-content" v-show="!isShow">
              <!-- 有多条数据展开时 -->
                <div class="dynamic flexwrap">
              <component :is="showWidget(item.type)"  v-for="item in registerAdd" :key="item.name" :struc="item"  />
                </div>
            </div>
          </div>
        </div>
      </ztitleBorder>

      <div class="select-area">
        <div class="select-info">
          <div class="title">就诊类型</div>
          <el-select 
            class="select-1"
            clearable
            v-model="visitType"
            filterable
            >
            <el-option
              v-for="item in optionsType"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <!-- <div class="select-info" v-show="visitType === '复诊'">
        <div class="title">就诊主诉</div>
        <el-select 
          class="select-2"
          clearable
          v-model="chiefComplaint"
          >
          <el-option
            v-for="item in optionComplaint"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
          </el-select>
        </div> -->
        <!-- <div class="select-info">
          <div class="title">就诊来源</div>
          <div style="display: flex; align-items: center">
            <el-select v-model="visitSource" placeholder="请选择" size="mini">
                <el-option
                  v-for="item in optionSource"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            <div style="padding-left: 10px; margin-bottom: 2px;">
              <el-input
                placeholder="请输入内容"
                class="input-1"
                size="mini"
                v-model="visitSourceDetails"
              >
              </el-input>
            </div>

          </div>
        </div> -->
        <div class="select-info">
          <div class="title">备注</div>
            <el-input class="input-1" v-model="remarks"></el-input>
        </div>
      </div>
      

      <div class="doctor">
        <span class="title">咨询师</span>
        <div class="radios-seach">
        <div class="radios">
          <el-radio-group   v-model="secondaryStatus" @change="handleSecondaryChange">
            <el-radio-button label="空闲"></el-radio-button>
            <el-radio-button label="咨询中"></el-radio-button>
            <el-radio-button label="不可约"></el-radio-button>
            <el-radio-button label="全部"></el-radio-button>
          </el-radio-group>
        </div>
        <div class="search-input">
          <el-input
            placeholder="搜索咨询师"
            suffix-icon="el-icon-search"
            class="input-1"
            v-model="secondarySearch"
            @keyup.enter="setSecondary"
            >
          </el-input>
        </div>
        </div>
        <div class="select-content">
          <div class="select-doctor" :class="{'d-active': (activeSecondary === index) && i.active}" v-for="(i, index) in secondaryList" :key="i.name"  @click="handleSecondaryItem(i,index)">
            <div class="info">
              <span>{{i.name}}</span>
              <span>等待: {{i.waitCount}}</span>
            </div>
            <div class="status">
              <span>{{i.status}}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="doctor">
        <span class="title">医生</span>
        <div class="radios-seach">
        <div class="radios">
          <el-radio-group   v-model="doctorStatus" @change="handleDoctorChange">
            <el-radio-button label="空闲"></el-radio-button>
            <el-radio-button label="咨询中"></el-radio-button>
            <el-radio-button label="不可约"></el-radio-button>
            <el-radio-button label="全部"></el-radio-button>
          </el-radio-group>
        </div>
        <div class="search-input">
          <el-input
            placeholder="搜索医生"
            suffix-icon="el-icon-search"
            class="input-1"
            v-model="doctorSearch"
            @keyup.enter="setDoctor"
            >
          </el-input>
        </div>
        </div>
        <div class="select-content">
          <div class="select-doctor" :class="{'d-active': (activeDoctor === index) && i.active}" v-for="(i, index) in doctorList" :key="i.name"  @click="handleDoctorItem(i,index)">
            <div class="info">
              <span>{{i.name}}</span>
              <span>等待: {{i.waitCount}}</span>
            </div>
            <div class="status">
              <span>{{i.status}}</span>
            </div>
          </div>
        </div>
      </div>
      
    </div>
    <div class="register-footer">
      <el-button class="btn-2" @click="cancel">取消</el-button>
      <el-button class="btn-1" @click="register">挂号</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Search, Plus, ArrowDown, ArrowRight, Male, Female, } from '@element-plus/icons-vue'
import { defineComponent, ref, PropType } from '@vue/runtime-core';
import useShowWidget from "../widget/usechoose";
import useRequet, { RespData } from "../../hook/network"
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"
import useConfgin from '../../hook/getconfig'
import searchItem, { SearchItemType } from "../searchinput/searchItem.vue"

import { Option ,AwaitStatus} from "../../types"
import { useRoute, useRouter } from 'vue-router';
import { debounce } from "../../utils/debounce"

import { ElMessage } from 'element-plus'
import { inject, onMounted, watch, watchEffect } from 'vue';
import eventBus from 'vue3-eventbus';

const ID = 523 // 挂号客户选择
interface RegisterEditInfo {
  id: number,
  detailType: string,
  medicalSources: string | null,
  medicalSourcesType: string,
  masterUserId: number | null,
  secondaryUserId: number,
  remark: string,
  record: SmallParts
  recordId: number
}

type SmallParts = {
  customerId: number
}
export default defineComponent({
  props: {
    registerInfo: {
      type: Object as PropType<RegisterEditInfo>
    },
    userId: {
      type: Number
    }
  },
  components: {
    ztitleBorder,
    searchItem,

    Male,
    Female,
    Search,
    Plus,
    ArrowDown,
    ArrowRight
  },
  setup(props, ctx) {
    
    const route = useRoute()
    const router = useRouter()
    const request = useRequet({ path: "" });
    const showWidget = useShowWidget;

    const registerinfo = useConfgin(ID)
    const registerAdd = registerinfo.groupDataAdd

    const info = ref('')
    const isShow = ref(false)
    const isShowPlan = ref(false)
    const personList = ref([] as any)
    // const isHide = ref(true)
    const sex = ref('')
    const cancel = () => {
      ctx.emit('cancel')
		}
    const handlebtn = () => {
        ctx.emit('handlebtn')
    }

    // 默认是添加
    const currentStatus = ref('ADD')
    const visitRecordID = ref()

    const visitType = ref('复诊')
    const visitSource = ref<string | null>(null)
    const visitSourceDetails = ref<string | null>(null)
    const chiefComplaint = ref()
    const remarks = ref('')

    const customerId = ref()
    const optionsType = ref([
      {
        id:'初诊',
        name: '初诊'
      },
      {
        id:'复诊',
        name: '复诊'
      },
    ])

    // 就诊类型下拉
    const getRegisteredType = () => {
      request.sendRequest({
        address: 'pay/order/getRegisteredType',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取就诊类型失败')
          optionsType.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    getRegisteredType()


    // 保存数据类型
    type RegisterSave = {
      id: number,
      customerId: number | null,
      medicalSourcesType: string | null,
      medicalSources: string | null,
      remark?: string,
      masterUserId: number | null,
      secondaryUserId: number | null,
      actionChief?: string,
      recordId?: number | null,
      registeredType: string
    }

    
    
    const register = () => {
      console.log('点击了保存')
      
      ctx.emit('clickRegisterStatus')
      let result = {} as RegisterSave
      result.customerId = customerId.value
      result.medicalSourcesType = visitSource.value || null
      result.medicalSources = visitSourceDetails.value || null
      result.remark = remarks.value
      result.masterUserId = masterUserId.value
      result.secondaryUserId = secondaryUserId.value
      result.registeredType = visitType.value
      result.recordId = chiefComplaint.value

      if(currentStatus.value === 'ADD') {
        request.sendRequest({
          address: 'pay/order/registered',
          params: result,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('添加挂号' + resp.msg)
            ElMessage.success('添加挂号' + resp.msg)

            cancel()

            if(route.name === 'DoctorToday') {
              eventBus.emit('refreshList')
            } else {
              router.push({name: 'DoctorToday'})
            }
            
            ctx.emit('reloadList')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('添加挂号' + resp.msg)
            
          },
          method: "POST",
        })
      }

      if(currentStatus.value === 'EDIT') {
        result.id = visitRecordID.value
        request.sendRequest({
          address: 'sick/record/updateRecordDetail',
          params: result,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('修改挂号' + resp.msg)
            ElMessage.success('修改挂号' + resp.msg)
            cancel()
            router.push({name: 'DoctorToday'})
            // 刷新列表
            ctx.emit('reloadList')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "POST",
        })
      }
      
    }
    const serachPerson = () => {
      request.sendRequest({
        address: 'customer/info/getSubCompanyCustomer',
        params: {
          value: info.value || ''
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          personList.value = resp.data.records
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })

      
    }
    const debounceSearch = debounce(serachPerson, 800)
    const querySearch = () => {
      if(info.value) {
        isShowPlan.value = true
        debounceSearch()
      } else {
        isShowPlan.value = false
      }
      
    }

    const handleItem = (data:SearchItemType) => {
      info.value = data.name
      sex.value = data.gender
      customerId.value = data.id

      getPersonInfo(data.id)

      isShowPlan.value = false

      // getoptionComplaint(data.id)
    }

    // 获取患者信息
    const getPersonInfo = (id: number) => {
      request.sendRequest({
        address: `customer/info/getCustomerInfo/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          let personInfo = resp.data;
          console.log(personInfo, 'personInfo')
          if(personInfo) {
            registerAdd.value.forEach((item: any) => {
              item.value = personInfo[item.name]
            })

            let lastRecord = resp.data.lastRecordsDetail
            // 补患者上次挂号信息
            if(lastRecord && Object.keys(lastRecord).length > 0) {
              visitType.value = lastRecord.detailType
              masterUserId.value = lastRecord.masterUserId
              secondaryUserId.value = lastRecord.secondaryUserId
              activeDoctor.value = doctorList.value.findIndex(i => {
                if(i.id === masterUserId.value) i.active = true;
                return i.id === masterUserId.value
              })
              activeSecondary.value = secondaryList.value.findIndex(i => {
                if(i.id === secondaryUserId.value) i.active = true;
                return i.id === secondaryUserId.value
              })
            }

            info.value = personInfo.name
            sex.value = personInfo.gender
            customerId.value = personInfo.id
          }
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    
    watchEffect(() => {
      onMounted(() => {
        if(props.userId) {
          getPersonInfo(Number(props.userId))
          customerId.value = props.userId
        }
        
      })
      
    })

    const handleShow = () => {
      isShow.value = !isShow.value
    }

    const doctorStatus = ref('全部')
    const doctorSearch = ref('')
    const doctorList = ref([] as AwaitStatus[])  // 医生
    const activeDoctor = ref(-1)
    const secondaryStatus = ref('全部')
    const secondarySearch = ref('')
    const secondaryList = ref([] as AwaitStatus[]) // 咨询师
    const secondaryUserId = ref()
    const masterUserId = ref()
    const optionSource = ref([] as Option[]) // 就诊来源
    const activeSecondary = ref(-1)
    const optionComplaint = ref([] as Option[])
    const handleDoctorItem = (data:any, i: number) => {
    
      data.active = !data.active
      
      activeDoctor.value = i

      if(data.active) {
        masterUserId.value = data.id
      } else {
        masterUserId.value = null
      }
      console.log(data, i, masterUserId.value)
    }
    const handleSecondaryItem = (data:any, i: number) => {
      data.active = !data.active

      activeSecondary.value = i
      if(data.active) {
        secondaryUserId.value = data.id
      } else {
        secondaryUserId.value = null
      }
      
    }

    const handleSecondaryChange = (val: string) => {
      secondaryStatus.value = val
      getConsultUser()
    }
    const setSecondary = () => {
      getConsultUser()
    }

    const handleDoctorChange = (val: string) => {
      doctorStatus.value = val
      getDoctorUser()
    }
    const setDoctor = () => {
      getDoctorUser()
    }

    const getConsultUser = () => {
      request.sendRequest({
        address: 'company/user/user/getConsultUserByStatus',
        params: {
          status: secondaryStatus.value || '',
          name: secondarySearch.value || ''
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取咨询师失败')
          secondaryList.value = resp.data
          secondaryList.value.map(i => i.active = false)

          activeSecondary.value = secondaryList.value.findIndex(i => i.id === secondaryUserId.value)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const getDoctorUser = () => {
        request.sendRequest({
          address: 'company/user/user/getDoctorUserByStatus',
          params: {
            name: doctorSearch.value || '',
            status: doctorStatus.value || '',
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '获取医生信息失败')
            doctorList.value = resp.data
            doctorList.value.map(i => i.active = false)
            activeDoctor.value = doctorList.value.findIndex(i => i.id === masterUserId.value)
            
            
            
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
          },
          method: "POST",
        })
    }

    const getoptionComplaint = (id: number) => {
      request.sendRequest({
        address: `pay/order/getCompanyUserRecord/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取主诉失败')
          optionComplaint.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    const getoptionSource = () => {
      request.sendRequest({
        address: 'pay/order/getRegisteredSourceType',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取来源失败')
          optionSource.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }


    getConsultUser()
    getDoctorUser()
    getoptionSource()

    


    // 当传入数据时 用户回显修改挂号数据
    let infoMag = props.registerInfo
    if(infoMag?.id) {
      currentStatus.value = 'EDIT'
      visitRecordID.value = infoMag.id

      visitType.value = infoMag.detailType
      visitSource.value = infoMag.medicalSourcesType || null
      visitSourceDetails.value = infoMag.medicalSources || null
      masterUserId.value = infoMag.masterUserId
      secondaryUserId.value = infoMag.secondaryUserId
      chiefComplaint.value = infoMag.recordId

      remarks.value = infoMag.remark

      let personID = infoMag.record.customerId
      customerId.value = personID

      getPersonInfo(personID)
      // getoptionComplaint(personID)
    }
    // const show = () => {
    //   isHide.value = false
    // }

    // const hide = () => {
    //   isHide.value = true
    // }
    return {
      cancel,
      register,
      sex,
      info,
      isShow,
      personList,
      querySearch,

      serachPerson,
      isShowPlan,
      registerAdd,

      visitType,
      visitSource,
      chiefComplaint,
      visitSourceDetails,
      remarks,
      optionsType,
      secondaryList,
      doctorList,
      optionSource,
      masterUserId,
      secondaryUserId,
      optionComplaint,

      handlebtn,
      handleShow,
      handleItem,

      doctorStatus,
      doctorSearch,
      activeDoctor,
      handleDoctorItem,
      secondaryStatus,
      secondarySearch,
      activeSecondary,
      handleSecondaryItem,

      setSecondary,
      setDoctor,
      handleSecondaryChange,
      handleDoctorChange,

      visitRecordID,
      currentStatus,

      showWidget,
      request
    }
  },
  methods: {
    bodyClose(e: Event) {
      if(this.$refs.searchArea &&  !(this.$refs.searchArea as any).contains(e.target)) {
        this.isShowPlan = false
      }
    }
  }
})
</script>

<style lang ="scss" scoped>
.register {
  display: flex;
  flex-direction: column;
  padding-top: 0;
  height: 100%;
  .register-content {
    padding: 20px;
    padding-top: 0px;
    height: calc(100% - 60px);
    overflow: auto;

    .select-area {
      display: flex;
      flex-wrap: wrap;
      border-top: 1px solid $mainColor;
      .select-info {
        padding: 10px;
        padding-left: 0;
        .title {
          font-size: $fontSize-1;
          font-weight: 600;
          color: $primaryText;
          padding-bottom: 5px;
        }
        
      }
    }

    .search-head {
    display: flex;
    width: 100%;
    .search {
      width: 100%;
      position: relative;
      .info-plan {
        position: absolute;
        width: 100%;
        height: 200px;
        box-shadow: 0 0 3px 0 #e9e9e9;
        z-index: 99;
        background: white;
        margin-top: 10px;
        overflow-y: auto;
        font-size: $fontSize-1;
      }
    }
    
    .btns {
      width: 30px;
      line-height: 30px;
      height: 30px;
      background: #e6e3e3;
      text-align: center;
      margin-left: 20px;
      border-radius: $radius-1;
      box-sizing: border-box;
      cursor: pointer;
    }
    }
    .search-ctx {
      padding-top: 10px;
      padding-bottom: 10px;
      width: 100%;
      display: flex;
      font-size: $fontSize;
      & > span {
        display: inline-block;
        flex: 1;
      }

      .callapse {
        width: 100%;
        background: #f4f4f5;
        box-sizing: border-box;
        .show-head {
          display: flex;
          height: 35px;
          line-height: 35px;
          cursor: pointer;
          .head-ctx {
            flex: 1;
            display: flex;
            /* justify-content: space-around; */
            & > span:nth-child(1) {
              padding-left: 10px;
              font-size: $fontSize-1;
              font-weight: 600;
            }
            .sex {
              padding-left: 8px;
              font-size: $fontSize-1;
            }
            .male-color {
              background: #409EFF;
              width: 20px;
              height: 20px;
              color: white;
              border-radius: 50%;
              position: relative;
              text-align: center;
              top: 5px;
            }
            .male-color::before {
              position: absolute;
              top: 3px;
              left: 3px;
            }

            .female-color {
              background: #F56C6C;
              width: 20px;
              height: 20px;
              color: white;
              border-radius: 50%;
              position: relative;
              text-align: center;
              top: 5px;
            }

            .female-color::before {
              position: absolute;
              top: 2px;
              left: 2px;
            }
          }
          .icon-btn {
            width: 35px;
            height: 35px;
            text-align: center;
          }
        }
        
        .show-content {
          width: 100%;
          background: white;
          & > span {
            padding: 10px;
            display: inline-block;
          }
        }
      }
    }

    .doctor {
      border-top: 1px solid $mainColor;
      box-sizing: border-box;
      padding-bottom: 10px;
      .title {
        font-size: $fontSize-1;
        font-weight: 600;
        margin-bottom: 10px;
        display: inline-block;
        padding-top: 10px;
        
      }
      .radios-seach {
          display: flex;
          align-content: center;
          .radios {
            padding-right: 30px;
            color: $regularText;
          }
      }
      .select-content {
        padding-top: 10px;
        display: flex;
        flex-wrap: wrap;
        .select-doctor {
          width: 120px;
          height: 50px;
          user-select: none;
          border-radius: $radius-1;
          border: 1px solid #e9e9e9;
          font-size: $fontSize;
          display: flex;
          flex-direction: column;
          align-content: center;
          margin-right: 5px;
          cursor: pointer;
          margin: 8px;
          box-sizing: border-box;
          color: $regularText;
          .info {
            height: 25px;
            line-height: 25px;
            display: flex;
            justify-content: space-around;
            align-items: center;
            

            & > span:nth-child(1) {
              font-size: $fontSize-1;
            }
          }

          .status {
            height: 25px;
            line-height: 25px;
            padding-left: 15px;
            color: $a8-Color;
          }

          .free {
            color: $mainColor;
          }
        }
      }
    }
    .callapse {
      .hide {
        height: 40px;
        line-height: 40px;
        /* border: 1px solid red; */
        border-top: 1px solid #e9e9e9;

        .hide-head {
          padding: 0 10px;
          display: flex;
          
          & > span:nth-child(1) {
            & > span {
              padding-right: 12px;
              font-size: 16px;
              font-weight: 600;
            }
            
            
          }

          & > span:nth-child(2) {
            margin-left: auto;
            & > i:nth-child(1) {
              padding: 10px;
              cursor: pointer;
            }
          }
        }
      }

      .show {
        .show-content {
          padding-left: 12px;
        }
      }
    }
  }
  .register-footer{
    width: 100%;
    height: 60px;
    line-height: 60px;
    box-shadow: 0 0 3px rgba(0, 0, 0, .3);
    flex: 1;
    text-align: right;
    .btn-1 {
      margin-right: 40px;
    }

  }
}

.d-active {
  background: $mainColor;
  color: white !important;
  border: none !important;
  .status {
    color: white !important; 
  }
}

.flexwrap {
  display: flex;
  flex-wrap: wrap;
}
</style>